import re
import smtplib
from email.mime.text import MIMEText

# 定义接收人的邮箱地址列表
recipient_email_list = []
recv_file_path = "recv_email.txt"

# 定义邮箱字符串校验正则
email_pattern = r"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$"
# 定义邮箱字符串校验函数
def is_email(email):
    return re.match(email_pattern, email) is not None

sender_email = "poplar_tang@163.com"
sender_password = "W809204933.tw"

def test_send_email():
    # 从文件recv_email.txt中读取接收人的邮箱地址
    with open(recv_file_path, "r") as f:
        for line in f:
            email_addr = line.strip()
            if not is_email(email_addr):
                print(f"无效的邮箱地址: {email_addr}")
                continue
            
            recipient_email_list.append(email_addr)        
    
    
    # recipient_email = "339402908@qq.com"
    
    # 如果接收人邮箱列表为空，则直接返回
    if len(recipient_email_list) == 0:
        print("接收人邮箱列表为空，无法发送邮件！")
        return
    
    subject = "测试邮件"
    body = "这是一封测试邮件，功能正常。嘎嘎"

    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = sender_email

    try:
        with smtplib.SMTP('smtp.163.com', 25) as server:
            server.starttls()
            server.login(sender_email, sender_password)
        
            # 循环发送邮件
            for recipient_email in recipient_email_list:
                msg['To'] = recipient_email
                server.send_message(msg)
                print("邮件发送成功 -> {}".format(recipient_email))
            else:
                print("所有邮件发送成功！")
    except Exception as e:
        print(f"邮件发送失败: {e}")

test_send_email()
